package com.tarena.lbs.basic.web.service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tarena.lbs.basic.web.repository.AreaRepository;
import com.tarena.lbs.pojo.basic.po.AreaPO;
import com.tarena.lbs.pojo.basic.vo.AreaVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AreaService {
    @Autowired
    private AreaRepository areaRepository;
    public List<AreaVO> getChildrenAreas(Long parentId) {
        List<AreaPO> pos=areaRepository.getChildreAreasByParentId(parentId);
        List<AreaVO> vos=null;
        if (CollectionUtils.isNotEmpty(pos)){
            vos=pos.stream().map(po->{
                AreaVO vo=new AreaVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        return vos;
    }

    public List<AreaVO> areaTree() {
        //1.list还是tree 需要查询的是area表格的所有数据
        List<AreaPO> pos=areaRepository.findAll();//拿到所有数据
        //2.在业务层组织一个方法 封装tree
        log.info("总区域数据量:{}",pos.size());
        return assembleAreaTree(pos);
    }
    private List<AreaVO> assembleAreaTree(List<AreaPO> pos) {
        //1.pos 入参是所有area数据 筛选省级列表 po->po.getParentId()==0
        List<AreaPO> provincePos=pos.stream().filter(po->po.getParentId()==0).collect(Collectors.toList());
        log.info("拿到了所有的省:{}",provincePos);
        List<AreaVO> provinceVos=pos2vos(provincePos);
        //2.筛选市级,某个省下的市级区域列表
        for (AreaVO provinceVo : provinceVos) {
            Long provinceId=provinceVo.getId();
            //3.继续从pos筛选该省下的所有市
            List<AreaPO> cityPos=pos.stream().filter(po->po.getParentId().equals(provinceId)).collect(Collectors.toList());
            //利用cityPos 封装vo的children列表
            List<AreaVO> cityVos=pos2vos(cityPos);
            provinceVo.setChildren(cityVos);
            log.info("我拿到了省:{},id:{}.下的所有市:{}",provinceVo.getName(),provinceId,cityPos);
            //筛选某个市下的区数据
            for (AreaVO cityVo : cityVos) {
                Long cityId=cityVo.getId();
                List<AreaPO> areaPos=pos.stream().filter(po->po.getParentId().equals(cityId)).collect(Collectors.toList());
                log.info("我拿到了市:{},id:{},下的所有区:{}",cityVo.getName(),cityId,areaPos);
                List<AreaVO> areaVos=pos2vos(areaPos);
                cityVo.setChildren(areaVos);
            }
        }
        return provinceVos;
    }

    private List<AreaVO> pos2vos(List<AreaPO> pos) {
        return pos.stream().map(po->{
            AreaVO vo=new AreaVO();
            BeanUtils.copyProperties(po,vo);
            return vo;
        }).collect(Collectors.toList());
    }
}
